//
//  CRNewsHomeViewController.m
//  NewAge
//
//  Created by dllo on 15/11/26.
//  Copyright © 2015年 ColorRevolution. All rights reserved.
//

#import "CRNewsHomeViewController.h"
#import "CRNewsHomeCollectionViewCell.h"
#import "CRHeaderModel.h"
#import "CRNewsModel.h"
#import "CRNewsDetailViewController.h"
#import "CRPicNewsViewController.h"
#import "CRSpecialNewsViewController.h"
#import "CRImportNewsViewController.h"


@interface CRNewsHomeViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, CRNewsHomeCollectionViewCellDelegate>
{
    NSInteger _page;
}

@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UIView *headBgView;
@property (nonatomic, strong) UIScrollView *headScrollView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;

@property (nonatomic, retain) NSArray *netArr;
@property (nonatomic, retain) NSArray *firstKeyArr;
@property (nonatomic, retain )NSMutableArray *currentArr;

@end

@implementation CRNewsHomeViewController



#pragma mark - init

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // 字典拼接数组
        self.firstKeyArr = @[@"T1348647853363", @"T1348648756099", @"T1348649580692", @"T1348650593803", @"T1350383429665", @"T1348649079062", @"T1348648517839"];
        // 请求链接数组
        self.netArr = @[@"http://c.m.163.com/nc/article/headline/T1348647853363/0-140.html", @"http://c.m.163.com/nc/article/list/T1348648756099/0-20.html", @"http://c.m.163.com/nc/article/list/T1348649580692/0-20.html", @"http://c.m.163.com/nc/article/list/T1348650593803/0-20.html", @"http://c.m.163.com/nc/article/list/T1350383429665/0-20.html", @"http://c.3g.163.com/nc/article/list/T1348649079062/0-20.html", @"http://c.3g.163.com/nc/article/list/T1348648517839/0-20.html"];
        
       
        
        
    }
    return self;
}



#pragma mark - createData

- (void)createData {
    [self checkNetWorkShowAlertWithblock:^(NetStatus status) {
        if (status == WWAN || status == WiFi) {
            [MBProgressHUDManager showHUDtoView:self.view string:@"加载中"];
            
            NSInteger i = self.collectionView.contentOffset.x / WIDTH;
            NSLog(@"%ld", i);
            [AfNetWorkingManager getInfoWithUrl:self.netArr[i] block:^(NSDictionary *resultDic, NSError *error) {
                NSDictionary *dic = resultDic;
                self.currentArr = [NSMutableArray array];
                if (dic[self.firstKeyArr[i]] != nil) {
                    self.currentArr = [CRNewsModel baseModelByArr:dic[self.firstKeyArr[i]]];
                    NSMutableArray *arr = [NSMutableArray array];
                    //            如果不加if判断有可能会crash
                    if ([self.currentArr[0] ads].count != 0) {
                        arr = [CRHeaderModel baseModelByArr:[self.currentArr[0] ads]];
                        [self.currentArr[0] setValue:arr forKey:@"ads"];
                    }
                    
                }
                NSArray *arr = [NSArray arrayWithArray:self.currentArr];
                
                for (CRNewsModel *tempNews in arr) {
                    if ([tempNews.skipType isEqualToString:@"live"] || [tempNews.skipType isEqualToString:@"video"]) {
                        [self.currentArr removeObject:tempNews];
                    }
                    
                    if ([tempNews.url_3w isEqualToString:@""]) {
                        [self.currentArr removeObject:tempNews];
                    }
                }
                
                if (self.currentArr.count != 0) {
                    
                }
                [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:i inSection:0]]];
                
                CRNewsHomeCollectionViewCell *cell = (CRNewsHomeCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
                cell.headCollectionView.contentOffset = CGPointMake(WIDTH, 0);
                
                [MBProgressHUDManager removeHUD];
            }];
        }
    }];
}



#pragma mark - createViews

- (void)createScrollView {
    
    UIView *headBlackView = [[UIView alloc] init];
    headBlackView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:headBlackView];
    
    self.headBgView = [[UIView alloc] init];
    _headBgView.backgroundColor = [UIColor colorWithRed:0.133f green:0.125f blue:0.125f alpha:1.00f];
    
    self.headScrollView = [[UIScrollView alloc] init];
    _headScrollView.contentSize = CGSizeMake(420 * WIDTH / 375.0, 0);
    _headScrollView.backgroundColor = [UIColor colorWithRed:0.133f green:0.125f blue:0.125f alpha:1.00f];
    
    [self.view addSubview:_headBgView];
    
    [self.headBgView addSubview:_headScrollView];
    
    UIButton *importButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [importButton setBackgroundImage:[UIImage imageNamed:@"iconfont-24hourservice.png"] forState:UIControlStateNormal];
    [importButton addTarget:self action:@selector(jumpToImportAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.headBgView addSubview:importButton];
    
    [headBlackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.mas_equalTo(24);
    }];
    
    [_headBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headBlackView.mas_bottom);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.mas_equalTo(40);
    }];
    
    [_headScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_headBgView).insets(UIEdgeInsetsMake(0, 70, 0, 50));
    }];
    
    [importButton mas_makeConstraints:^(MASConstraintMaker *make) {
        Top(headBlackView.mas_bottom, 5);
//        Left(_headScrollView.mas_right, 5);
        HequalView(importButton);
        Right(_headBgView.mas_right, -5);
        Bottom(_headBgView.mas_bottom, -5);
    }];
    
    NSArray *titleArr = @[@"头条", @"财经", @"科技", @"时尚", @"娱乐", @"体育"];
    for (NSInteger i = 0; i < titleArr.count; i++) {
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(70 * WIDTH / 375.0 * i + 10 * WIDTH / 375.0, 10, 50 * WIDTH / 375.0, 20)];
        titleLabel.text = titleArr[i];
        if (i == 0) {
            titleLabel.textColor = [UIColor redColor];
        }
        titleLabel.textColor = [UIColor whiteColor];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.userInteractionEnabled = YES;
        titleLabel.tag = 1000 + i;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectTitleAction:)];
        [titleLabel addGestureRecognizer:tap];
        
        tap.numberOfTapsRequired = 1;
        tap.numberOfTouchesRequired = 1;
        
        [_headScrollView addSubview:titleLabel];
        
        UIView *titleFootView = [[UIView alloc] initWithFrame:CGRectMake(70 * WIDTH / 375.0 * i, 37, 70 * WIDTH / 375.0, 3)];
        if (i == 0) {
            titleFootView.backgroundColor = [UIColor redColor];
        }
        titleFootView.tag = 2000 + i;
        [_headScrollView addSubview:titleFootView];
    }
    
}

- (void)createCollectionView {
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    _flowLayout.minimumInteritemSpacing = 0;
    _flowLayout.minimumLineSpacing = 0;
    _flowLayout.itemSize = CGSizeMake(WIDTH, HEIGHT - 64);
    _flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:_flowLayout];
    _collectionView.contentSize = CGSizeMake(WIDTH * 6, 0);
    _collectionView.pagingEnabled = YES;
    _collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_collectionView];
    
    [_collectionView registerClass:[CRNewsHomeCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_headBgView.mas_bottom);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    
    [self createData];
}



#pragma mark - ViewMethod

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self createScrollView];
    [self createCollectionView];
    
//    self.timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(changePage) userInfo:nil repeats:YES];
    

}


- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.hidden = YES;
    
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
}

- (void)viewWillDisappear:(BOOL)animated {
    _collectionView.dataSource = nil;
    _collectionView.delegate = nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}



#pragma mark - GestureRecognizerAction

- (void)selectTitleAction:(UITapGestureRecognizer *)tap {
    NSLog(@"%ld", tap.view.tag);
    for (NSInteger i = 0; i < 6; i ++) {
        if (tap.view.tag - 1000 == i) {
            UILabel *label = (UILabel *)[self.view viewWithTag:tap.view.tag];
            label.textColor = [UIColor redColor];
            UIView *view = [self.view viewWithTag:label.tag + 1000];
            view.backgroundColor = [UIColor redColor];
        }
        else {
            UILabel *label = (UILabel *)[self.view viewWithTag:i + 1000];
            label.textColor = [UIColor whiteColor];
            UIView *view = [self.view viewWithTag:label.tag + 1000];
            view.backgroundColor = [UIColor colorWithRed:0.133f green:0.125f blue:0.125f alpha:1.00f];
        }
    }
    
    if ((tap.view.tag - 1000) > 2) {
        _headScrollView.contentOffset = CGPointMake(70 * WIDTH / 375.0 * (tap.view.tag - 1000) / 2, 0);
    }
    else {
        _headScrollView.contentOffset = CGPointMake(0, 0);
    }
    _collectionView.contentOffset = CGPointMake(WIDTH * (tap.view.tag - 1000), 0);
    _page = tap.view.tag - 1000;
    [self createData];
}



#pragma mark - collectionViewDateSource & Delegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 6;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CRNewsHomeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    if (self.currentArr) {
        cell.currentArr = self.currentArr;
    }
    [self.collectionView.panGestureRecognizer requireGestureRecognizerToFail:cell.headCollectionView.panGestureRecognizer];
    
    cell.delegate = self;
    
    return cell;
}



#pragma mark - scrollViewDelegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == _collectionView) {
        for (NSInteger i = 0; i < 6; i ++) {
            if (scrollView.contentOffset.x / WIDTH == i) {
                UILabel *label = (UILabel *)[self.view viewWithTag:i + 1000];
                label.textColor = [UIColor redColor];
                UIView *view = [self.view viewWithTag:label.tag + 1000];
                view.backgroundColor = [UIColor redColor];
            }
            else {
                UILabel *label = (UILabel *)[self.view viewWithTag:i + 1000];
                label.textColor = [UIColor whiteColor];
                UIView *view = [self.view viewWithTag:label.tag + 1000];
                view.backgroundColor = [UIColor colorWithRed:0.133f green:0.125f blue:0.125f alpha:1.00f];
            }
        }
        if (scrollView.contentOffset.x > WIDTH * 2) {
            _headScrollView.contentOffset = CGPointMake(70 * WIDTH / 375.0 * scrollView.contentOffset.x / WIDTH / 2, 0);
        }
        else {
            _headScrollView.contentOffset = CGPointMake(0, 0);
        }
    }
    _page = scrollView.contentOffset.x / WIDTH;
    [self createData];
}



#pragma mark - buttonAction

- (void)jumpToImportAction:(UIButton *)button {
    CRImportNewsViewController *inVC = [[CRImportNewsViewController alloc] init];
    [self.navigationController pushViewController:inVC animated:YES];
}

#pragma mark - pushDelegate

- (void)pushToDetailWithStr:(NSString *)str title:(NSString *)title {
    CRNewsDetailViewController *ndVC = [[CRNewsDetailViewController alloc] init];
    ndVC.str = str;
    ndVC.myTitle = title;
    [self.navigationController pushViewController:ndVC animated:YES];
}

- (void)pushToPicDetailWithStr:(NSString *)str title:(NSString *)title {
    NSString *firstStr = [str substringFromIndex:9];
    NSString *secondStr = [str substringWithRange:NSMakeRange(4, 4)];
    NSString *url = [NSString stringWithFormat:@"http://c.3g.163.com/photo/api/set/%@/%@.json", secondStr, firstStr];
    NSLog(@"%@", url);
    CRPicNewsViewController *picVC = [[CRPicNewsViewController alloc] init];
    
    picVC.url = url;
    picVC.myTitle = title;
    
    [self.navigationController pushViewController:picVC animated:YES];
    
}

- (void)pushToSpecialDetailWithStr:(NSString *)str title:(NSString *)title {
    NSString *strURL = [NSString stringWithFormat:@"http://c.3g.163.com/nc/special/%@.html", str];
    CRSpecialNewsViewController *snVC = [[CRSpecialNewsViewController alloc] init];
    snVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:snVC animated:YES];
    snVC.url = strURL;
    snVC.specialID = str;
    snVC.myTitle = title;
}


#pragma mark - changPageAction

- (void)changePage {
    CRNewsHomeCollectionViewCell *cell = (CRNewsHomeCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:self.collectionView.contentOffset.x / WIDTH inSection:0]];
    if (cell.headCollectionView.contentOffset.x == WIDTH * ([self.currentArr[0] ads].count + 2)) {
        cell.headCollectionView.contentOffset = CGPointMake(WIDTH, 0);
    }
    else {
        cell.headCollectionView.contentOffset = CGPointMake(cell.headCollectionView.contentOffset.x + WIDTH, 0);
    }
    
}



//- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
//    
//    switch (interfaceOrientation) {
//        case UIInterfaceOrientationPortrait:
//            //home健在下
//            
//            _flowLayout.itemSize = CGSizeMake(WIDTH, HEIGHT - 64);
//            _collectionView.contentSize = CGSizeMake(WIDTH * 6, 0);
//            _collectionView.contentOffset = CGPointMake(WIDTH * _page, 0);
//            [_collectionView reloadData];
//            break;
//        case UIInterfaceOrientationPortraitUpsideDown:
//            //home健在上
//            
//            _flowLayout.itemSize = CGSizeMake(WIDTH, HEIGHT - 64);
//            _collectionView.contentSize = CGSizeMake(WIDTH * 6, 0);
//            _collectionView.contentOffset = CGPointMake(WIDTH * _page, 0);
//            [_collectionView reloadData];
//            break;
//        case UIInterfaceOrientationLandscapeLeft:
//            //home健在左
//            _flowLayout.itemSize = CGSizeMake(WIDTH, HEIGHT - 64);
//            _collectionView.contentSize = CGSizeMake(WIDTH * 6, 0);
//            _collectionView.contentOffset = CGPointMake(WIDTH * _page, 0);
//            [_collectionView reloadData];
//
//            break;
//        case UIInterfaceOrientationLandscapeRight:
//            //home健在右
//            _flowLayout.itemSize = CGSizeMake(WIDTH, HEIGHT - 64);
//            _collectionView.contentSize = CGSizeMake(WIDTH * 6, 0);
//            _collectionView.contentOffset = CGPointMake(WIDTH * _page, 0);
//            [_collectionView reloadData];
//
//            break;
//        default:
//            break;
//            
//    }
//    NSLog(@"%ld", _page);
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
